#!/bin/bash

pm() {
  which brew >>/dev/null 2>&1
  if [ "$?" = "0" ]; then
    # ignore -yqq in mac
    local args=""
    for arg in $@; do
      case $arg in
      -yqq) ;;

      *)
        args="$args $arg"
        ;;
      esac
    done

    brew $args
    return
  fi

  which yum >>/dev/null 2>&1
  if [ "$?" = "0" ]; then
    sudo yum $@
    return
  fi

  which apt >>/dev/null 2>&1
  if [ "$?" = "0" ]; then
    sudo apt $@
    return
  fi
}

# node npm
pm::npm() {
  load_nvm() {
    local NVM_DIR=$HOME/.nvm
    if [ -s "$NVM_DIR/nvm.sh" ]; then
      . "$NVM_DIR/nvm.sh" # This loads nvm
    fi
  }

  is_nodejs_installed() {
    load_nvm

    which node >> /dev/null 2>&1
    if [ "$?" = "0" ]; then
      echo "true"
    else
      echo "false"
    fi
  }

  if [ "$(is_nodejs_installed)" = "false" ]; then
    zpackage install nodejs
  fi

  load_nvm

  # @TODO
  if [ "$(net::is_google_visitable)" = "false" ]; then
    export NPM_CONFIG_REGISTRY=https://registry.npm.taobao.org
  fi

  npm $@
}

# pm_nvm() {
#   # @TODO
#   if [ "$(net::is_google_visitable)" = "false" ]; then
#     export NVM_NODEJS_ORG_MIRROR=https://npm.taobao.org/dist
#   fi

#   nvm $@
# }

export -f pm

# export -f pm_nvm
export -f pm::npm